package com.jier.controller.console;

import com.jier.annotation.ValidateField;
import com.jier.annotation.ValidateGroup;
import com.jier.common.Result;
import com.jier.common.exception.HttpParamException;
import com.jier.common.permission.Permission;
import com.jier.common.util.StringUtil;
import com.jier.controller.BaseController;
import com.jier.entities.SystemModule;
import com.jier.entities.SystemRole;
import com.jier.entities.SystemUser;
import com.jier.enums.RoleType;
import com.jier.model.PageParam;
import com.jier.model.SystemModuleParam;
import com.jier.service.ISystemModuleService;
import com.jier.service.ISystemRoleService;
import com.jier.vo.admin.FieldVo;
import com.jier.vo.admin.SystemModuleVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统模块控制器
 *
 * @author jie_r
 * @date 2018/03/08
 */
@RestController
@RequestMapping("/console/systemModules")
public class SystemModuleController extends BaseController {
    @Autowired
    private ISystemModuleService systemModuleService;

    @Autowired
    private ISystemRoleService systemRoleService;

    /**
     * 系统模块首页-管理页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/index.html", method = RequestMethod.GET)
    @ApiOperation(value = "系统模块首页-管理页面", hidden = true, httpMethod = "GET")
    @Permission(code = "010301", content = "系统模块首页-管理页面")
    public ModelAndView indexPage() throws Exception {
        return new ModelAndView("/systemModule/systemModules");
    }

    /**
     * 编辑系统模块-管理页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/edit.html", method = RequestMethod.GET)
    @ApiOperation(value = "编辑系统模块-管理页面", hidden = true, httpMethod = "GET")
    @Permission(code = "010303", content = "编辑系统模块-管理页面")
    public ModelAndView editModulePage(Integer id) throws Exception {
        ModelAndView mv = new ModelAndView("/systemModule/edit_systemModule");
        SystemModule systemModule = systemModuleService.getById(id);
        mv.addObject("systemModule", systemModule);
        return mv;
    }

    /**
     * 新增系统模块-管理页面
     *
     * @param parent
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add.html", method = RequestMethod.GET)
    @ApiOperation(value = "新增系统模块-管理页面", hidden = true, httpMethod = "GET")
    @Permission(code = "010302", content = "新增系统模块-管理页面")
    public ModelAndView addModulePage(Integer parent) throws Exception {
        ModelAndView mv = new ModelAndView("/systemModule/add_systemModule");
        mv.addObject("parent", parent);
        return mv;
    }

    /**
     * 获取系统父级模块
     *
     * @param pageParam
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/parent", method = RequestMethod.GET, produces = "application/json;")
    @ApiOperation(value = "获取系统父级模块", httpMethod = "GET", produces = "application/json;")
    @Permission(code = "010301", content = "获取系统父级模块")
    public ResponseEntity<Result<SystemModule>> getSystemParentModule(PageParam pageParam) throws Exception {
        Result<SystemModule> result = systemModuleService.getSystemParentModule(getPage(pageParam));
        return ok(result);
    }

    /**
     * 获取父级模块的系统子级模块
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{id}/child", method = RequestMethod.GET, produces = "application/json;")
    @ApiOperation(value = "获取父级模块的系统子级模块", httpMethod = "GET", produces = "application/json;")
    @Permission(code = "010301", content = "获取父级模块的系统子级模块")
    public ResponseEntity<List<SystemModule>> getSystemChildModule(@PathVariable Integer id) throws Exception {
        List<SystemModule> result = systemModuleService.getSystemChildModule(id);
        return ok(result);
    }

    /**
     * 获取菜单
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/nav", method = RequestMethod.GET, produces = "application/json;")
    @ApiOperation(value = "获取菜单", httpMethod = "GET", produces = "application/json;")
    public ResponseEntity<List<SystemModuleVo>> updateHotel(HttpSession session) throws Exception {
        // 获取登陆用户角色
        SystemUser systemUser = (SystemUser) session.getAttribute("currentUser");
        SystemRole systemRole = systemRoleService.getSystemRole(systemUser.getId());
        if (systemRole == null) {
            throw new HttpParamException("登陆用户没有角色");
        }
        // 一级菜单
        List<SystemModule> firstLevelNaves;
        // 二级菜单
        List<SystemModule> secondLevelNaves;
        if (systemRole.getType() == RoleType.superAdmin.ordinal()) {
            firstLevelNaves = systemModuleService.getFirstLevelNaves();
            secondLevelNaves = systemModuleService.getSecondLevelNaves();
        } else {
            firstLevelNaves = systemModuleService.getFirstLevelNavesByRoleId(systemRole.getId());
            secondLevelNaves = systemModuleService.getSecondLevelNavesByRoleId(systemRole.getId());
        }
        List<SystemModuleVo> firstLevelNavVoes = new ArrayList<SystemModuleVo>();
        for (SystemModule firstLevelNav : firstLevelNaves) {
            List<SystemModuleVo> secondLevelNavVoes = new ArrayList<SystemModuleVo>();
            for (SystemModule secondLevelNav : secondLevelNaves) {
                if (secondLevelNav.getParent().equals(firstLevelNav.getId())) {
                    secondLevelNavVoes.add(new SystemModuleVo(secondLevelNav));
                }
            }
            if (secondLevelNavVoes.size() == 0) {
                continue;
            }
            SystemModuleVo systemModuleVo = new SystemModuleVo(firstLevelNav);
            systemModuleVo.setChildren(secondLevelNavVoes);
            firstLevelNavVoes.add(systemModuleVo);
        }
        return ok(firstLevelNavVoes);
    }

    /**
     * 编辑系统模块
     *
     * @param moduleParam
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.POST, produces = "application/json;")
    @ApiOperation(value = "编辑系统模块", httpMethod = "POST", produces = "application/json;")
    @ValidateGroup(fields = {
            @ValidateField(index = 0, paramName = "名字", filedName = "moduleParam.name", notNull = true, maxLen = 10),
            @ValidateField(index = 0, paramName = "模块编号", filedName = "moduleParam.number", notNull = true, regStr = "^\\d{4}$"),
            @ValidateField(index = 0, paramName = "父级模块", filedName = "moduleParam.parent", notNull = true),
            @ValidateField(index = 0, paramName = "状态", filedName = "moduleParam.status", notNull = true),
    })
    @Permission(code = "010303", content = "编辑系统模块")
    public ResponseEntity<Boolean> updateSystemModule(SystemModuleParam moduleParam, @PathVariable Integer id) throws Exception {
        if (moduleParam.getParent().equals(0)) {
            // 父级模块，图标不能为空
            if (StringUtil.isEmpty(moduleParam.getIcon())) {
                throw new HttpParamException("父级模块，图标为空");
            }
            moduleParam.setHref("#");
        } else {
            // 子级模块，链接不能为空
            if (StringUtil.isEmpty(moduleParam.getHref())) {
                throw new HttpParamException("子级模块，链接为空");
            }
            moduleParam.setIcon(null);
        }
        SystemModule systemModule = systemModuleService.getById(id);
        if (systemModule == null) {
            throw new HttpParamException("系统模块信息不存在");
        }
        SystemModule systemModuleTmp = systemModuleService.getSystemModuleByNumber(moduleParam.getNumber());
        if (systemModuleTmp != null && !systemModuleTmp.getId().equals(systemModule.getId())) {
            throw new HttpParamException("系统模块，编号【" + moduleParam.getNumber() + "】已存在");
        }
        systemModuleTmp = systemModuleService.getSystemModuleByName(moduleParam.getName());
        if (systemModuleTmp != null && !systemModuleTmp.getId().equals(systemModule.getId())) {
            throw new HttpParamException("系统模块，名字【" + moduleParam.getName() + "】已存在");
        }
        systemModule.setName(moduleParam.getName());
        systemModule.setNumber(moduleParam.getNumber());
        systemModule.setParent(moduleParam.getParent());
        systemModule.setIcon(moduleParam.getIcon());
        systemModule.setHref(moduleParam.getHref());
        systemModule.setStatus(moduleParam.getStatus());
        systemModuleService.updateById(systemModule);
        return ok(Boolean.TRUE);
    }

    /**
     * 新增系统模块
     *
     * @param moduleParam
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json;")
    @ApiOperation(value = "新增系统模块", httpMethod = "POST", produces = "application/json;")
    @ValidateGroup(fields = {
            @ValidateField(index = 0, paramName = "名字", filedName = "moduleParam.name", notNull = true, maxLen = 10),
            @ValidateField(index = 0, paramName = "模块编号", filedName = "moduleParam.number", notNull = true, regStr = "^\\d{4}$"),
            @ValidateField(index = 0, paramName = "父级模块", filedName = "moduleParam.parent", notNull = true),
            @ValidateField(index = 0, paramName = "状态", filedName = "moduleParam.status", notNull = true),
    })
    @Permission(code = "010302", content = "新增系统模块")
    public ResponseEntity<Boolean> addSystemModule(SystemModuleParam moduleParam) throws Exception {
        if (moduleParam.getParent().equals(0)) {
            // 父级模块，图标不能为空
            if (StringUtil.isEmpty(moduleParam.getIcon())) {
                throw new HttpParamException("父级模块，图标为空");
            }
            moduleParam.setHref("#");
        } else {
            // 子级模块，链接不能为空
            if (StringUtil.isEmpty(moduleParam.getHref())) {
                throw new HttpParamException("子级模块，链接为空");
            }
            moduleParam.setIcon(null);
        }
        SystemModule systemModule = systemModuleService.getSystemModuleByNumber(moduleParam.getNumber());
        if (systemModule != null) {
            throw new HttpParamException("系统模块，编号【" + moduleParam.getNumber() + "】已存在");
        }
        systemModule = systemModuleService.getSystemModuleByName(moduleParam.getName());
        if (systemModule != null) {
            throw new HttpParamException("系统模块，名字【" + moduleParam.getName() + "】已存在");
        }
        systemModule = new SystemModule();
        systemModule.setName(moduleParam.getName());
        systemModule.setNumber(moduleParam.getNumber());
        systemModule.setParent(moduleParam.getParent());
        systemModule.setIcon(moduleParam.getIcon());
        systemModule.setHref(moduleParam.getHref());
        systemModule.setStatus(moduleParam.getStatus());
        systemModule.setUpdateDate(new Date());
        systemModule.setCreateDate(new Date());
        // 获取最后位模块
        SystemModule systemModuleLast = systemModuleService.getLastSystemModule(moduleParam.getParent());
        if (systemModuleLast == null) {
            systemModule.setSortOrder(1);
        } else {
            systemModule.setSortOrder(systemModuleLast.getSortOrder() + 1);
        }
        systemModuleService.save(systemModule);
        return ok(Boolean.TRUE);
    }

    /**
     * 获取系统模块字段
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/field", method = RequestMethod.GET, produces = "application/json;")
    @ApiOperation(value = "获取系统模块字段", httpMethod = "GET", produces = "application/json;")
    public ResponseEntity<List<FieldVo>> getSystemModuleField() throws Exception {
        List<SystemModule> result = systemModuleService.getSystemModuleField();
        List<FieldVo> fields = result.stream().map(systemModule -> new FieldVo(systemModule.getId(), systemModule.getName())).collect(Collectors.toList());
        return ok(fields);
    }
}
